<template>
	<BasicModal v-bind="$attrs" z-index="1000" style="z-index:999" @register="registerModal" :width="1200" :height="800"
		title="选择定位" @ok="confirmSelect" :helpMessage="['提示1', '提示2']">
		<div class="input-card" style="display: flex;">
			<a-button class="btn" @click="drawPolygon" style="margin-bottom: 5px" >绘制多边形</a-button>
			<!-- 		<button class="btn" @click="getPolygon" style="margin-bottom: 5px">获取多边形</button>
					<button class="btn" @click="createPolygon" style="margin-bottom: 5px">创建多边形</button> -->
			<a-button class="btn" @click="editorPolygon" style="margin-bottom: 5px">编辑多边形</a-button>
			<a-button class="btn" @click="saveEditedPolygon" style="margin-bottom: 5px"
				:disabled="!editMode">保存编辑</a-button>
				
				<!-- <a-button class="btn" @click="deleteLast" style="margin-bottom: 5px">删除最后一个</a-button>
				<a-button class="btn" @click="restoreLast" style="margin-bottom: 5px">删错了还原</a-button>
				
 -->
		</div>
		<div id="container" style=" border: 1px solid red;"></div>
		<div id="pickerBox">
			<input id="pickerInput" placeholder="输入关键字选取地点" />
			<div id="poiInfo"></div>
		</div>
	</BasicModal>
</template>
<script lang="ts" setup>
	import AMapLoader from '@amap/amap-jsapi-loader';
	import { shallowRef } from '@vue/reactivity';
	import { defineComponent, ref, onMounted } from 'vue';
	import { useMessage } from '/@/hooks/web/useMessage';
	import { BasicModal, useModalInner } from '/@/components/Modal';
  import {getCityLngLatByCityId} from './modal.api';
	import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
	const map = shallowRef(null)
	const mouseTool = shallowRef(null)
	const polyEditor = shallowRef(null)
	const path = ref([
	])

	const polygonOverlay = shallowRef(null)
	const editMode = ref(false)
	const cityInfo = ref("")
	const citylll= ref(  [] as  Array<any>)

	const latLog = ref('' as string)
	var polygonPath = [];

	// 创建面覆盖物
	var polygon;
	const getCurrentLocation = () => {
		const that = this;
		let geolocation = new AMap.Geolocation({
			enableHighAccuracy: true,
			zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
		});
		geolocation.getCurrentPosition(function (status, result) {
			//备注：getCurrentPosition方法会调用超时或失败：
			//Get geolocation time out：浏览器定位超时，包括原生的超时，可以适当增加超时属性的设定值以减少这一现象。
			//另外还有个别浏览器（如google Chrome浏览器等）本身的定位接口是黑洞，通过其请求定位完全没有回应，也会超时返回失败。
			//Get geolocation failed：定位失败，Chrome、火狐以及部分套壳浏览器接入的定位服务在国外，有较大限制，失败率高。
			console.log(status, result);
			if (status == 'complete') {

			} else {
				//失败后可使用getCityInfo获取非精准定位（具体到省市）
			}
		});
	}
	const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
		setModalProps({ zIndex: 1000 })
		latLog.value = data.latLog
    cityInfo.value=data.cityInfo
    let lll= await getCityLngLatByCityId({cityId:cityInfo.value});
   
    citylll.value=lll.split(",")
		mapInit()
	})

	 const mapInit = () => {
    //这里先通过城市id获取该城市的经纬度，然后返回经纬度在显示当前城市的地理位置
    console.log("----")
		AMapLoader.load({
			key: "d363dce36e0cf588721ffa48268bb5fd",
			version: "2.0",
			plugins: [],
		}).then((AMap) => {
			let latLogs = [], l1, l2;
			console.log(latLog)
			if (typeof latLog.value != "string") {
				polygonPath = latLog.value
				l1 = citylll.value[0]
				l2 = citylll.value[1]
			} else {

				if (latLog.value == '') {
				l1 = citylll.value[0]
				l2 = citylll.value[1]
				} else {
					latLogs = latLog.value.split(",")
					l1 = latLogs[0]
					l2 = latLogs[1]
				}

			}
			console.log(latLogs,polygonPath)
			if (latLog.value == '') {
				polygonPath=[]
			}
			map.value = new AMap.Map("container", {
				viewMode: "3D",
				zoom: 12,
				center: [l1, l2],
			})

			AMap.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.HawkEye', 'AMap.MapType', 'AMap.MouseTool', 'AMap.Polygon', 'AMap.PolyEditor', 'AMap.Geolocation'], function () {
				const scale = new AMap.Scale()
				map.value.addControl(scale)
				map.value.addControl(new AMap.ToolBar())
				map.value.addControl(new AMap.HawkEye())
				map.value.addControl(new AMap.MapType())
			})
			mouseTool.value = new AMap.MouseTool(map.value)
			map.value.on('click', function (ev) {
				// 地图点击事件
			})
			if (latLogs.length > 1) {
				console.log('102')
				polygonPath=[]
				let lat, log;
				for (let i = 0; i < latLogs.length; i++) {
					if (i % 2 == 0) {
						lat = latLogs[i]
					} else {
						log = latLogs[i]
					}
					if (i % 2 != 0 && i > 0) {
						polygonPath.push(new AMap.LngLat(lat, log))
					}
				}
			}

			if (polygonPath.length > 1) {
				polygon = new AMap.Polygon({
					path: polygonPath
				});
				map.value.add(polygon);
				var overlays = map.value.getAllOverlays("polygon");
				console.log(overlays)
				polygonOverlay.value = overlays[0]
			}

		}).catch(e => {
			console.log(e)
		})

	}

	// 绘制多边形
	const drawPolygon = () => {
		if (mouseTool.value) {
			mouseTool.value.polygon({
				strokeColor: "#000",
				strokeOpacity: 1,
				strokeWeight: 2,
				strokeOpacity: 1,
				fillColor: '#1791fc',
				fillOpacity: 0.1,
				strokeStyle: "solid",
			})
			mouseTool.value.on('draw', function (event) {
				// 获取绘制的覆盖物
				polygonOverlay.value = event.obj
				console.log(polygonOverlay.value)
			})
		}
	}
	const emit = defineEmits(['register', 'successConfirm']);
	var latLot;
	const { createMessage } = useMessage();
	function confirmSelect() {
		/* 	if (form.address == '') {
				return createMessage.warning('请先选择经纬度');;
			} */
		emit('successConfirm', polygonOverlay.value.getPath());
		polygonOverlay.value = null;
		polyEditor.value = null
		polygonPath=[]
		closeModal()
	}

	// 获取绘制的多边形
	const getPolygon = () => {
		if (polygonOverlay.value) {
			// 在控制台中查看多边形的路径坐标
			console.log("多边形路径坐标:", polygonOverlay.value.getPath())
		}
	}
	
	/**
	 * 还原删除的一个
	 */
	const restoreLast=()=>{
		
	}
	/**
	 * 删除最后一个
	 */
	const deleteLast=()=>{
		
	}
	
	

	// 创建多边形
	const createPolygon = () => {
		var polygon = new AMap.Polygon({
			path: path.value,
			// strokeColor: "#FF33FF",
			// strokeWeight: 1,
			// strokeOpacity: 0.2,
			// fillOpacity: 0.4,
			// fillColor: '#1791fc',
			zIndex: 50,
			bubble: true,
		})
		map.value.add([polygon])
		polygonOverlay.value = polygon
	}

	// 多边形编辑
	const editorPolygon = () => {
		console.log(polygonOverlay.value)
		if (polygonOverlay.value) {
			polyEditor.value = null
			
			//	if (!polyEditor.value) {
			// 创建多边形编辑工具
			polyEditor.value = new AMap.PolyEditor(map.value, polygonOverlay.value)
			//}
			
			// 进入编辑模式
			polyEditor.value.open()
			editMode.value = true
		}
	}

	// 保存编辑后的多边形
	const saveEditedPolygon = () => {
		if (editMode.value && polyEditor.value) {
			// 退出编辑模式
			polyEditor.value.close()
			editMode.value = false
			polyEditor.value = null
		}
	}
</script>

<style>
	#pickerBox {
		position: absolute;
		z-index: 9999;
		top: 50px;
		right: 30px;
		width: 300px;
	}

	#pickerInput {
		width: 200px;
		padding: 5px 5px;
	}

	#poiInfo {
		background: #fff;
	}

	.amap_lib_placeSearch .poibox.highlight {
		background-color: #CAE1FF;
	}

	.amap_lib_placeSearch .poi-more {
		display: none !important;
	}

	#container {
		padding: 0px;
		margin: 0px;
		width: 100%;
		height: 600px;
	}

	.info {
		padding: .5rem .75rem;
		margin-bottom: 1rem;
		border-radius: .25rem;
		position: fixed;
		top: 15rem;
		background-color: white;
		width: auto;
		z-index: 100;
		min-width: 20%;
		border-width: 0;
		right: 40%;
		box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
	}

	.input-item {
		position: relative;
		display: -ms-flexbox;
		display: flex;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
		-ms-flex-align: center;
		align-items: center;
		width: 100%;
		height: 3rem;
	}

	.input-item-prepend {
		margin-right: -1px;
	}

	.input-item-text {
		text-align: justify;
		padding: 0.4rem 0.7rem;
		display: inline-block;
		text-justify: distribute-all-lines;
		text-align-last: justify;
		-moz-text-align-last: justify;
		-webkit-text-align-last: justify;
		-ms-flex-align: center;
		align-items: center;
		margin-bottom: 0;
		font-size: 1rem;
		font-weight: 400;
		line-height: 1.5;
		color: #495057;
		text-align: center;
		white-space: nowrap;
		background-color: #e9ecef;
		border: 1px solid #ced4da;
		border-radius: 0.25rem;
		border-bottom-right-radius: 0;
		border-top-right-radius: 0;
	}

	.input-item-text,
	input[type=text],
	input[type=date],
	select {
		height: calc(2.2rem + 2px);
	}
</style>